package LeetCode.leetcode105;

import java.util.HashMap;

public class Review1 {
    HashMap<Integer, Integer> map;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        map = new HashMap<>();
        for(int i = 0; i < inorder.length; i++){
            map.put(inorder[i], i);
        }
        return buildTree2(preorder, inorder, 0, preorder.length - 1, 0, preorder.length - 1);
    }
    public TreeNode buildTree2(int[] preorder, int[] inorder, int preLeft, int preRight, int inLeft, int inRight) {
        if (preLeft > preRight || inLeft > inRight) {
            return null;
        }
        // 前序遍历中的第一个节点就是根节点
        int preorder_root = preLeft;
        // 在中序遍历中定位根节点
        int inorder_root = map.get(preorder[preorder_root]);
        // 得到左子树中的节点数目
        int size_left_subtree = inorder_root - inLeft;
        TreeNode root = new TreeNode(preorder[preLeft]);
        root.left = buildTree2(preorder, inorder, preLeft + 1, preLeft + size_left_subtree ,inLeft, inorder_root - 1);
        root.right = buildTree2(preorder, inorder, preLeft  + size_left_subtree + 1, preRight, inorder_root + 1, inRight);
        return  root;
    }

}
